package rpc.server;

import lombok.extern.slf4j.Slf4j;
import rpc.common.enumeraion.ResponseCode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import rpc.packet.RpcRequest;
import rpc.packet.RpcResponse;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

@Slf4j
//通过反射进行request方法调用
public class RequestHandler {

    public Object handle(RpcRequest rpcRequest, Object service) {
        Object result = null;
        try {
            result = invokeTargetMethod(rpcRequest, service);
            log.debug("服务: {} 成功调用方法: {}", rpcRequest.getInterfaceName(), rpcRequest.getMethodName());
        } catch (IllegalAccessException | InvocationTargetException e) {
           log.debug("调用或发送时有错误发生");
           return RpcResponse.fail(ResponseCode.METHOD_HANDLE_ERROR);
        }
        return result;
    }

    //调用目标方法
    private Object invokeTargetMethod(RpcRequest rpcRequest, Object service) throws IllegalAccessException, InvocationTargetException {
        Method method;
        try {
            method = service.getClass().getMethod(rpcRequest.getMethodName(), rpcRequest.getParamTypes());
        } catch (NoSuchMethodException e) {
            return RpcResponse.fail(ResponseCode.METHOD_NOT_FOUND);
        }
        //执行
        return method.invoke(service, rpcRequest.getParameters());
    }

}
